package com.nmf.site.biz.pay.wechat.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nmf.site.biz.pay.wechat.conf.HwWechatConfVo;
import com.nmf.site.common.excep.KideException;
import com.nmf.site.common.excep.KideExpCode;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class TenSSLHttpUtil {
	private static Logger log = LoggerFactory.getLogger(TenSSLHttpUtil.class);
	public static SSLConnectionSocketFactory sslsf;

	public static String sendHttpPost(SortedMap<String, String> parmap, String reqUrl) throws Exception {
		if (sslsf == null) {
			initSSLFactory();
		}
		StringBuffer rspText = new StringBuffer();
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try {
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();

			Set<String> kset = parmap.keySet();
			for (String keystr : kset) {
				formparams.add(new BasicNameValuePair(keystr, parmap.get(keystr)));
			}

			StringEntity entity = new StringEntity(TenpayUtil.getRequestXml(parmap));

			HttpPost httpPost = new HttpPost(reqUrl);
			httpPost.addHeader("Connection", "keep-alive");
			httpPost.addHeader("Accept", "*/*");
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.addHeader("Host", "dev.wechat.huangbaoche.com");
			httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
			httpPost.addHeader("Cache-Control", "max-age=0");
			httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpPost.setEntity(entity);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				HttpEntity rspEntity = response.getEntity();

				if (entity != null) {
					System.out.println("Response content length: " + rspEntity.getContentLength());
					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rspEntity.getContent()));
					String text;
					while ((text = bufferedReader.readLine()) != null) {
						rspText.append(text);
					}

				}
				EntityUtils.consume(entity);
			} catch (Exception e) {
				log.error("", e);
				throw new KideException(KideExpCode.REQ_ERROR,e.toString());
			} finally {
				response.close();
			}
		} catch (Exception e) {
			log.error("", e);
			throw new KideException(KideExpCode.REQ_ERROR,e.toString());
		} finally {
			httpclient.close();
		}
		return rspText.toString();
	}

	public static void initSSLFactory() throws Exception {
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		String path = TenSSLHttpUtil.class.getResource("/").getPath();
		FileInputStream instream = new FileInputStream(new File(path + File.separator + "apiclient_cert.p12"));
		try {
			keyStore.load(instream, HwWechatConfVo.mch_id.toCharArray());
		} finally {
			instream.close();
		}
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, HwWechatConfVo.mch_id.toCharArray()).build();
		// Allow TLSv1 protocol only
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	}

}
